import { WereWolfChecker } from "@/werewolf/components/seerChecker";
import { WereWolfTimeLimiter } from "@/werewolf/components/timeLimiter";
import { WereWolfModule } from "@/werewolf/module";
import { WereWolfRole } from "@/werewolf/player";
import { ItemStack } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { RandomUtils } from "@sapi-game/utils";
import { WereWolfPlayerTeleport } from "../components/playerteleporter";

export class WereWolfSeerPhase extends WereWolfModule.State {
    get seer() {
        return this.context.players.find(
            (p) => !p.dead && p.role == WereWolfRole.Seer
        );
    }

    override onEnter(): void {
        const seer = this.seer;
        this.addComponent(Timer, {
            initialTime: seer ? 40 : RandomUtils.intRange(5, 15),
        })
            .addComponent(WereWolfTimeLimiter, {
                getPlayers: () => {
                    if (!this.seer) return [];
                    return [this.seer];
                },
                onEnd: () => this.next(),
            })
            .addComponent(WereWolfChecker, { itemId: "werewolf:seer" });

        if (this.context.config.restrictMode) {
            this.addComponent(WereWolfPlayerTeleport);
            this.getComponent(WereWolfPlayerTeleport).tpAllToHouse();
        }

        this.addComponents(this.context.map.phaseViews.seer);
    }

    StartPhase() {
        const seer = this.seer;
        if (seer) {
            seer.giveItem(new ItemStack("werewolf:seer"));
        }
        this.getComponent(Timer).start();
    }

    next() {
        this.getComponent(Timer).stop();
        this.seer?.clear("werewolf:seer");
        this.popState();
    }
}
